<?php
namespace app\index\controller;

use app\admin\model\Admin;
use app\common\controller\Encrypt;
use app\common\controller\Jwt;
use app\index\model\Areas;
use app\index\model\Cities;
use app\index\model\Member;
use app\index\model\Provinces;
use think\App;
use think\Controller;
use Naixiaoxin\ThinkWechat\Facade;
use think\facade\Config;

class Index extends Controller{
//    protected $middleware = ['Wechat'];
    protected static $officialAccount = null;
    protected static $key = null;
    public function __construct(App $app = null){
        parent::__construct($app);
        self::$officialAccount = Facade::officialAccount();
        self::$key = Config::get('app.signature');
    }

    public function index(){
        // 先初始化微信
        self::$officialAccount->server->push(function($message){
            return 'hello,world';
        });
        self::$officialAccount->server->serve()->send();
    }

    public function js_api($url=''){
        if(!$url){
            return json(['code'=>1,'msg'=>'请填写调用域名']);
        }
        self::$officialAccount->jssdk->setUrl($url);
        $json =  self::$officialAccount->jssdk->buildConfig([
            'scanQRCode',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'openLocation',
            'previewImage',
            'getLocation',
            'chooseWXPay',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'hideMenuItems'
        ],false);
        return $json;
    }

    /**
     * 发起请求
     * @param string $url
     * @return \think\response\Json
     */
    public function oauth($url=''){
        if(!$url){
            return json(['code'=>1,'msg'=>'请填写跳转地址']);
        }
        self::$officialAccount->oauth->setRedirectUrl($url);
        $response = self::$officialAccount->oauth->scopes(['snsapi_userinfo'])
            ->redirect()->getTargetUrl();
        return json(['code'=>0,'msg'=>'成功','redirect_url'=>$response]);
    }

    /**
     * @param string $code
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function user1($code=''){
        if($code){
           $user = self::$officialAccount->oauth->user();
           if($user) {
               $member = new Member();
               $validate = new \app\index\validate\Member();
               $open_id = $user->getId();
               $user1 = $member::field('id,nickname,open_id,avatar,sex,address')
                   ->where('open_id', 'eq', $open_id)->find();
               if ($user1) {
                   session('user', $user);
                   session('_open_id', $open_id);
                   return json(['code' => 0, 'msg' => '授权成功', 'data' => $user1->toArray()]);
               } else {
                   $original = $user->getOriginal();
                   $name = filterEmoji($user->getNickname());
                   $data = [
                       'username' => $name,
                       'nickname' => $name,
                       'open_id' => $open_id,
                       'information' => '他很懒没有留下任何脚印',
                       'address' => "{$original['country']}_{$original['province']}_{$original['city']}",
                       'proid'=>$this->getProCode($original['province']),
                       'cityid'=>$this->getCityCode($original['city']),
                       'sex' => $original['sex'],
                       'avatar' => $user->getAvatar(),
                       'create_time'=>time()
                   ];
                   if (!$validate->check($data)) {
                       return json(['code' => 1, 'msg' => $validate->getError()]);
                   }
                   if (!$member->insert($data)) {
                       return json(['code' => 1, 'msg' => '保存用户失败']);
                   }
                   $user1 = $member::field('id,nickname,open_id,avatar,sex,address')
                       ->where('open_id', 'eq', $open_id)->find();
                   session('user', $user);
                   session('_open_id', $open_id);

                   return json(['code' => 0, 'msg' => '授权成功', 'data' => $user1->toArray()]);
               }
           }
        }else{
            return json(['code' => 1, 'msg' => '请传入微信的code']);
        }
    }

    /**
     * 用户授权
     * @param string $code
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function user($code=''){
        if($code){
            $user = self::$officialAccount->oauth->user();
            if($user) {
                $member = new Member();
                $validate = new \app\index\validate\Member();
                $open_id = $user->getId();
                $user1 = $member::field('id,nickname,avatar,sex,address')
                    ->where('open_id', 'eq', $open_id)->find();
                if ($user1) {
                    $jwt = $this->jwt($user1);
                    $result = $user1->toArray();
                    $result['token']=$jwt;
                    $result['user_code']=Encrypt::encode($user1['id']);
                    unset($result['id']);
                    return json(['code' => 0, 'msg' => '授权成功', 'data' => $result]);
                } else {
                    $original = $user->getOriginal();
                    $name = filterEmoji($user->getNickname());
                    $data = [
                        'username' => $name,
                        'nickname' => $name,
                        'open_id' => $open_id,
                        'information' => '他很懒没有留下任何脚印',
                        'address' => "{$original['country']}_{$original['province']}_{$original['city']}",
                        'proid'=>$this->getProCode($original['province']),
                        'cityid'=>$this->getCityCode($original['city']),
                        'sex' => $original['sex'],
                        'avatar' => $user->getAvatar(),
                        'create_time'=>time()
                    ];
                    if (!$validate->check($data)) {
                        return json(['code' => 1, 'msg' => $validate->getError()]);
                    }
                    if (!$member->insert($data)) {
                        return json(['code' => 1, 'msg' => '保存用户失败']);
                    }
                    $user1 = $member::field('id,nickname,avatar,sex,address')
                        ->where('open_id', 'eq', $open_id)->find();
                    $jwt = $this->jwt($user1);
                    $result = $user1->toArray();
                    $result['token']=$jwt;
                    $result['user_code']=Encrypt::encode($user1['id']);
                    unset($result['id']);
                    return json(['code' => 0, 'msg' => '授权成功', 'data' => $result]);
                }
            }
        }else{
            return json(['code' => 1, 'msg' => '请传入微信的code']);
        }
    }

    /**
     * 签验
     * @param null $user
     * @return bool|string
     */
    protected function jwt($user=null){
        if(!$user){
           return false;
        }
        $payload['user_name'] = $user->nickname;
        $payload['user_id'] = $user->id;
        $payload['expire_time'] = Config::get('app.expire_time');
        $token = $this->_createAPIToken($payload);
        return $token;
    }

    public function login(){
        $payload['user_name'] = '魏巍';
        $payload['user_id'] = 1;
        $payload['expire_time'] = Config::get('app.expire_time');
        $token = $this->_createAPIToken($payload);
        $code = Encrypt::encode($payload['user_id']);
        return json(['code'=>1,'data'=>[
            'token'=>$token,
            'code'=>$code,
            'decode'=>Encrypt::decode($code)
        ]]);
    }

    /**
     * token
     * @return array|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function oauth_callback(){
        $open_id = session('_open_id');
        if($open_id){
            $member = new Member();
            $user1 = $member::field('id,nickname,open_id,avatar,sex,address')
                ->where('open_id', 'eq', $open_id)->find();
            if($user1){
                return json(['code'=>0,'msg'=>'授权成功','data'=>$user1->toArray()]);
            }else{
                return json(['code'=>1,'msg'=>'授权失败']);
            }
        }else{
            return json(['code'=>1,'msg'=>'授权失败']);
        }
    }

    public function getProCode($pro=''){
        $m = new Provinces();
        $list = $m
           ->whereLike('province',"%{$pro}省",'OR')
           ->whereLike('province',"%{$pro}市",'OR')
           ->find();
        return $list['provinceid'];
    }

    public function getCityCode($pro=''){
        $m = new Cities();
        $list = $m
            ->whereLike('city',"%{$pro}市")
            ->find();
        return $list['cityid'];
    }

    public function getAreaCode($pro=''){
        $m = new Areas();
        $list = $m
            ->whereLike('province',"%{$pro}县",'OR')
            ->whereLike('province',"%{$pro}区",'OR')
            ->find();
        return $list['areaid'];
    }


    /**
     * 生成Token
     * @param $payload
     * @param string $alg
     * @return string
     */
    private function _createAPIToken($payload,$alg = 'HS256'){
        $jwtObj = new Jwt();
        $key = self::$key; //key
        $payload['uid'] = $payload['user_id'];//(必填参数,值自定义)
        $payload['iat'] = $_SERVER['REQUEST_TIME'];//签发时间(必填参数)
        $payload['exp'] = $_SERVER['REQUEST_TIME'] + $payload['expire_time'];//过期时间(必填参数)
        $jwt = $jwtObj::encode($payload, $key ,$alg);
        return $jwt;
    }

    public function encode($str='123'){
        return Encrypt::encode($str);
    }
}
